<template>
  <div class="p-2">
    <el-card shadow="never">
      <el-tabs v-model="queryParams.type" @tab-click="handleChangeType">
        <el-tab-pane v-for="model in modelTypeList" :label="model.label" :name="model.name">
          <el-collapse v-model="activeModel" @change="handleChange" accordion>
            <el-collapse-item v-for="item in openKeyList" :key="item.id" :title="item.name" :name="item.id">
              <el-card shadow="never" style="max-width: 600px">
                <el-form ref="openKeyFormRef" v-loading="buttonLoading" :model="form" :rules="rules" label-width="auto"
                         style="max-width: 600px">
                  <el-form-item label="AppId">
                    <el-input v-model="form.appId"/>
                  </el-form-item>
                  <el-form-item label="AppKey">
                    <el-input v-model="form.appKey"/>
                  </el-form-item>
                  <el-form-item label="AppSecret">
                    <el-input v-model="form.appSecret"/>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="submitForm" type="primary">更新</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup name="OpenKey" lang="ts">
import {listOpenKey, getOpenKey, delOpenKey, addOpenKey, updateOpenKey} from '@/api/gpt/openKey';
import {OpenKeyVO, OpenKeyQuery, OpenKeyForm} from '@/api/gpt/openKey/types';
import type {CollapseModelValue, TabsPaneContext} from 'element-plus'

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const openKeyList = ref<OpenKeyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const activeModel = ref('')

const modelTypeList = ref([
  {name: 1, label: '文字模型'},
  {name: 2, label: '图像模型'},
  {name: 3, label: '视觉模型'},
  {name: 4, label: '语音模型'}
])

const queryFormRef = ref<ElFormInstance>();
const openKeyFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OpenKeyForm = {
  id: undefined,
  type: undefined,
  value: undefined,
  name: undefined,
  appId: undefined,
  appKey: undefined,
  appSecret: undefined,
  sort: undefined,
}
const data = reactive<PageData<OpenKeyForm, OpenKeyQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: 1,
    value: undefined,
    name: undefined,
    appId: undefined,
    appKey: undefined,
    appSecret: undefined,
    sort: undefined,
    params: {}
  },
  rules: {
    id: [
      {required: true, message: "主键不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "模型类型不能为空", trigger: "change"}
    ],
    value: [
      {required: true, message: "模型值不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "模型名称不能为空", trigger: "blur"}
    ],
    appSecret: [
      {required: true, message: "App密钥不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

const handleChangeType = (tab: TabsPaneContext, event: Event) => {
  queryParams.value.type = tab.props.name as number
  getList()
}

const handleChange = async (val: CollapseModelValue) => {
  await getModelInfo()
}

/** 查询模型配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOpenKey(queryParams.value);
  openKeyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  if (res.rows.length > 0) {
    activeModel.value = res.rows[0].id as string
  } else {
    activeModel.value = ''
  }
  await getModelInfo()
}

const getModelInfo = async () => {
  reset()
  if (activeModel.value != '') {
    const res = await getOpenKey(activeModel.value)
    form.value = res.data
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  //openKeyFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OpenKeyVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加模型配置";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: OpenKeyVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getOpenKey(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改模型配置";
}

/** 提交按钮 */
const submitForm = async () => {
  buttonLoading.value = true;
  if (form.value.id) {
    await updateOpenKey(form.value).finally(() => buttonLoading.value = false);
  } else {
    await addOpenKey(form.value).finally(() => buttonLoading.value = false);
  }
  proxy?.$modal.msgSuccess("修改成功");
  dialog.visible = false;
  await getList();
}

/** 删除按钮操作 */
const handleDelete = async (row?: OpenKeyVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除模型配置编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delOpenKey(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('gpt/openKey/export', {
    ...queryParams.value
  }, `openKey_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
